package com.windoent.yugioh.ui.fragment.saishi.baoming;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.MyApplication;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.banner.ImageAdapter;
import com.windoent.yugioh.adapter.brvah.BaoMingSecondCaiPanAdapter;
import com.windoent.yugioh.adapter.brvah.TopCaiPanListAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.CaiPanListData;
import com.windoent.yugioh.bean.GameStatusRoleBean;
import com.windoent.yugioh.bean.GeneralBean;
import com.windoent.yugioh.bean.UserBean;
import com.windoent.yugioh.bean.eventbus.FragmentActivityMessageEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.meinfo.JudgeAuthActivity;
import com.windoent.yugioh.ui.activity.meinfo.JudgeAuthRealNameActivity;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.SimpleUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.RoundImageView;
import com.windoent.yugioh.widget.dialog.CanSaiBaoMingApplyCaiPanDialog;
import com.windoent.yugioh.widget.dialog.ExitGameReasonDialog;
import com.windoent.yugioh.widget.dialog.SucessFailAutoDismissDialog;
import com.windoent.yugioh.widget.dialog.SureNotDialog;
import com.youth.banner.Banner;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/17 14:14
 * desc   :报名裁判
 */
public class BaoMingCaiPanFragment extends BaseFragment {
    private RelativeLayout mRlJudge;
    private RoundImageView mIvJudge;
    private TextView mTvJudgeName;
    private TextView mTvJudgeId;
    private RecyclerView mRecyclerView;
    private TextView mTvApplayMainJudge;
    private TextView mTvApplayJudge;
    private TextView mTvApplayJudgeReviewing;
    private TextView mTvApplayJudgeExit;
    private RecyclerView mRecyclerViewTop;
    private TopCaiPanListAdapter topCaiPanListAdapter;
    private BaoMingSecondCaiPanAdapter caiPanAdapter;
    private LinearLayout mLlNoMainJudge;
    private LinearLayout mLlBtn;
    private LinearLayout mLlNoJudge;
    private SmartRefreshLayout mSmartLayout;
    private Banner mBanner;
    private ImageAdapter bannerAdapter;
    private int refereeApply;//是否申请过
    private CaiPanListData.DataBean.MatchInfoBean matchInfo;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_saishi_baoming_caipan;
    }

    @Override
    protected void initEventAndData() {
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        mTvApplayMainJudge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String string = MyApplication.getInstance().getUserInfo();
                if (BaseMethod.notNull(string) && BaseUtils.isJSONValid(string)) {
                    UserBean userBean = gson.fromJson(string, UserBean.class);
                    boolean real = userBean.isReal();
                    boolean referee = userBean.isReferee();
                    if (!referee) {
                        showApplyRefreeIdify(real, 1);
                    } else {
                        //申请主裁判(（1:主裁判 2：裁判）)
                        if (matchInfo != null) {
                            showApplayDialog(matchInfo, "1");
                        }
                    }
                }

            }
        });
        mTvApplayJudge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String string = MyApplication.getInstance().getUserInfo();
                if (BaseMethod.notNull(string) && BaseUtils.isJSONValid(string)) {
                    UserBean userBean = gson.fromJson(string, UserBean.class);
                    boolean real = userBean.isReal();
                    boolean referee = userBean.isReferee();
                    if (!referee) {
                        showApplyRefreeIdify(real, 2);
                    } else {
                        //裁判
                        if (matchInfo != null) {
                            showApplayDialog(matchInfo, "2");
                        }
                    }
                }
            }
        });
        mTvApplayJudgeReviewing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //审核中
                showSucessDialog(true, getString(R.string.string_submit_sucess_reviewing), false);
            }
        });
        mTvApplayJudgeExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                existDialog();
            }
        });
    }

    //没有裁判身份
    private void showApplyRefreeIdify(boolean real, int type) {
        MyApplication.refreeType = 0;
        SureNotDialog dialog = new SureNotDialog(mContext);
        dialog.setTvContent(getString(R.string.string_no_judge_identy_warning));
        dialog.setYesStr(getString(R.string.string_to_shiming_renzhen));
        dialog.setNoStr(getString(R.string.dl_cancel));
        dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                if (!real) {
                    Intent intent = new Intent(mContext, JudgeAuthRealNameActivity.class);
                    intent.putExtra("type", type);
                    startActivity(intent);
                } else {
                    //裁判认证
                    Intent intent = new Intent(mContext, JudgeAuthActivity.class);
                    intent.putExtra("type", type);
                    startActivity(intent);
                }
            }
        });
        dialog.show();
    }

    //裁判取消裁判
    private void existDialog() {
        ExitGameReasonDialog dialog = new ExitGameReasonDialog(mContext);
        dialog.setOnclickListener(new ExitGameReasonDialog.onClickListener() {
            @Override
            public void onClick(String string) {
                caipanDelete(string);
            }
        });
        dialog.show();
    }

    //取消裁判
    private void caipanDelete(String string) {
        showLoadingDialog("");
        PhoneLive.caipanDelete(getUserToken(), id, string, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            showSucessDialog(true, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_exit_judge_game)), true);
                        } else {
                            showSucessDialog(false, BaseMethod.notNullDefaultValueNull(msg), true);
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    private void showApplayDialog(CaiPanListData.DataBean.MatchInfoBean info, String type) {
        MyApplication.refreeType = 0;
        CanSaiBaoMingApplyCaiPanDialog dialog = new CanSaiBaoMingApplyCaiPanDialog(mContext);
        dialog.setTitle(getString(R.string.string_apply_game_judge_warn));
        dialog.setTimeStr(BaseMethod.notNullDefaultValueNull(info.getTime()));
        dialog.setPlaceStr(getString(R.string.string_gane_place_colon) + BaseMethod.notNullDefaultValueNull(info.getAddress()));
        dialog.setPhoneStr(BaseMethod.notNullDefaultValueNull(info.getPhone()));
        dialog.setYesOnclickListener(new CanSaiBaoMingApplyCaiPanDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                caipanApplay(type);
            }
        });
        dialog.show();
    }

    //申请裁判
    private void caipanApplay(String type) {
        showLoadingDialog("");
        PhoneLive.caipanApplay(getUserToken(), id, type, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            showSucessDialog(true, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_submit_sucess_reviewing)), false);
                        } else {
                            showSucessDialog(false, BaseMethod.notNullDefaultValueNull(msg), false);
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //申请成功
    private void showSucessDialog(boolean sucess, String msg, boolean isExit) {
        SucessFailAutoDismissDialog dialog = new SucessFailAutoDismissDialog(mContext, new SucessFailAutoDismissDialog.OnInterface() {
            @Override
            public void onDissmiss() {
                if (sucess) {
                    fresh(id);
                }
            }
        });
        if (sucess)
            dialog.setTvContent(true, R.drawable.drawable_dialog_sucess, msg, "", "");
        else
            dialog.setTvContent(false, R.drawable.drawable_dialog_fail, isExit ? getString(R.string.string_caipan_exit_fail) : getString(R.string.string_caipan_apply_fail), "", msg);
        dialog.show();
    }

    private void initData() {
        initRvAdapter();
        initTopRvAdapter();
        initBanner();
        mLlBtn.setVisibility(View.GONE);
    }

    private void initBanner() {
        bannerAdapter = new ImageAdapter(null);
        mBanner.setAdapter(bannerAdapter)
                .addBannerLifecycleObserver(this);//添加生命周期观察者
    }

    private void initRvAdapter() {
        mRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 5));
        mRecyclerView.setNestedScrollingEnabled(false);
        caiPanAdapter = new BaoMingSecondCaiPanAdapter();
        mRecyclerView.setAdapter(caiPanAdapter);
    }

    private void initTopRvAdapter() {
        mRecyclerViewTop.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerViewTop.setNestedScrollingEnabled(false);
        topCaiPanListAdapter = new TopCaiPanListAdapter();
        mRecyclerViewTop.setAdapter(topCaiPanListAdapter);
    }

    private void initView() {

        mLlBtn = (LinearLayout) mView.findViewById(R.id.ll_btn);
        mBanner = (Banner) mView.findViewById(R.id.banner);
        mRlJudge = (RelativeLayout) mView.findViewById(R.id.rl_judge);
        mIvJudge = (RoundImageView) mView.findViewById(R.id.iv_judge);
        mTvJudgeName = (TextView) mView.findViewById(R.id.tv_judge_name);
        mTvJudgeId = (TextView) mView.findViewById(R.id.tv_judge_id);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
        mRecyclerViewTop = (RecyclerView) mView.findViewById(R.id.recycler_view_top);
        mLlNoMainJudge = (LinearLayout) mView.findViewById(R.id.ll_no_main_judge);
        mTvApplayMainJudge = (TextView) mView.findViewById(R.id.tv_applay_main_judge);
        mTvApplayJudge = (TextView) mView.findViewById(R.id.tv_applay_judge);
        mTvApplayJudgeReviewing = (TextView) mView.findViewById(R.id.tv_applay_judge_reviewing);
        mTvApplayJudgeExit = (TextView) mView.findViewById(R.id.tv_applay_judge_exit);
        mLlNoJudge = (LinearLayout) mView.findViewById(R.id.ll_no_judge);
        mSmartLayout = (SmartRefreshLayout) mView.findViewById(R.id.smart_layout);
    }

    public static BaoMingCaiPanFragment newsInstance(String id, String response) {
        //创建 Bundle
        BaoMingCaiPanFragment fragment = new BaoMingCaiPanFragment();
        Bundle lBundle = new Bundle();
        lBundle.putString("id", id);
        lBundle.putString("response", response);
        fragment.setArguments(lBundle);
        return fragment;
    }


    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "赛事报名中裁判tab");
        }
        getDetailsId();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "赛事报名中裁判tab");
        }
    }

    private String id = "";

    //获取activity传值id
    private void getDetailsId() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            id = bundle.getString("id");
            String response = bundle.getString("response");
            initSmart(id);
            fresh(id);
        }
    }

    //获取赛事状态角色
    private void getGameStatusRole(String id) {
        showLoadingDialog("");
        PhoneLive.getGameStatusRole(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int idres) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GameStatusRoleBean json = gson.fromJson(response, GameStatusRoleBean.class);
                            if (json != null) {
                                GameStatusRoleBean.DataBean data = json.getData();
                                if (data != null) {
                                    String role = data.getRole();
                                    int statusid = data.getStatusid();
                                    if (statusid != 2 && statusid != 8) {
                                        //发送eventbus粘性事件
                                        FragmentActivityMessageEvent event = new FragmentActivityMessageEvent();
                                        event.setMessage(1);
                                        event.setRole(role);
                                        event.setStatusId(statusid);
                                        EventBus.getDefault().postSticky(event);
                                    } else if (statusid == 2) {
                                        getCaiPanList(id);
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    private void initSmart(String id) {
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(id);
            }
        });
    }

    //裁判列表
    private void fresh(String id) {
        getGameStatusRole(id);
    }

    private void getCaiPanList(String id) {
        showLoadingDialog("");
        PhoneLive.getCaiPanList(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                showTopCaiPan(false);
                showOneCaiPan(false, true);
                mSmartLayout.finishRefresh(false);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            mSmartLayout.finishRefresh(true);
                            CaiPanListData fromJson = gson.fromJson(response, CaiPanListData.class);
                            if (fromJson != null) {
                                CaiPanListData.DataBean data = fromJson.getData();
                                if (data != null) {
                                    matchInfo = data.getMatchInfo();
                                    List<String> banner = data.getBanner();
                                    if (bannerAdapter != null &&banner != null && banner.size() > 0) {
                                        mBanner.setVisibility(View.VISIBLE);
                                        bannerAdapter.setDatas(banner);
                                        bannerAdapter.notifyDataSetChanged();
                                    } else {
                                        mBanner.setVisibility(View.GONE);
                                    }
                                    int type = MyApplication.refreeType;
                                    if (type == 1) {
                                        //主裁判
                                        //申请主裁判(（1:主裁判 2：裁判）)
                                        if (matchInfo != null) {
                                            showApplayDialog(matchInfo, "1");
                                        }
                                    } else if (type == 2) {
                                        //裁判
                                        if (matchInfo != null) {
                                            showApplayDialog(matchInfo, "2");
                                        }
                                    }
                                    refereeApply = data.getApplyRefereeStatusID();//1未参加2审核中3通过
                                    String role = data.getRole();
                                    showBottomBtn(role, refereeApply);
                                    List<CaiPanListData.DataBean.RefereeBean> referee = data.getReferee();//主裁判审核
                                    List<CaiPanListData.DataBean.RefereeBean> umpire = data.getUmpire();
                                    if (referee != null && referee.size() > 0) {
                                        showTopCaiPan(true);
                                        topCaiPanListAdapter.setNewInstance(referee);
                                    } else {
                                        showTopCaiPan(false);
                                    }
                                    if (umpire != null) {
                                        if (umpire.size() == 1) {
                                            showOneCaiPan(true, false);
                                            CaiPanListData.DataBean.RefereeBean umpireBean = umpire.get(0);
                                            if (umpireBean != null) {
                                                mTvJudgeName.setText(BaseMethod.notNullDefaultValueNull(umpireBean.getNickname()));
                                                mTvJudgeId.setText(getString(R.string.string_user_info_id) + BaseMethod.notNullDefaultValueNull(umpireBean.getRefereeViewId() + ""));
                                                SimpleUtils.loadImageForView(mContext, mIvJudge, umpireBean.getAvatar(), R.drawable.img_official_avatar_android);
                                            }
                                        } else if (umpire.size() > 1) {
                                            showOneCaiPan(false, false);
                                            caiPanAdapter.setNewInstance(umpire);
                                        } else {
                                            showOneCaiPan(false, true);
                                        }
                                    }
                                }
                            }
                        } else mSmartLayout.finishRefresh(false);
                    } catch (JSONException e) {
                        mSmartLayout.finishRefresh(false);
                        e.printStackTrace();
                    }
                } else {
                    mSmartLayout.finishRefresh(false);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    private void showOneCaiPan(boolean oneCaiPan, boolean bNull) {
        mRecyclerView.setVisibility(!bNull && !oneCaiPan ? View.VISIBLE : View.GONE);
        mRlJudge.setVisibility(!bNull && oneCaiPan ? View.VISIBLE : View.GONE);
        mLlNoJudge.setVisibility(bNull ? View.VISIBLE : View.GONE);
    }

    private void showTopCaiPan(boolean show) {
        mRecyclerViewTop.setVisibility(show ? View.VISIBLE : View.GONE);
        mLlNoMainJudge.setVisibility(!show ? View.VISIBLE : View.GONE);
    }

    //底部按钮显示隐藏

    /**
     * 底部按钮
     * "customer":"商家",
     * "customerReferee":"商家+主裁判",
     * "notJoin":"没有参加",
     * "pReferee":"主裁判",
     * "player":"选手",
     * "referee":"裁判",
     * "visitor":"游客"
     * "pending":"角色正在审核中"
     * statusId 1未参加2审核中3通过
     */
    private void showBottomBtn(String role, int statusId) {
        boolean notJoin = BaseMethod.notNull(role) && role.equals("notJoin");
        boolean pReferee = BaseMethod.notNull(role) && role.equals("pReferee");
        boolean player = BaseMethod.notNull(role) && role.equals("player");
        boolean referee = BaseMethod.notNull(role) && role.equals("referee");
        boolean customer = BaseMethod.notNull(role) && role.equals("customer");
        boolean customerReferee = BaseMethod.notNull(role) && role.equals("customerReferee");
        boolean pending = BaseMethod.notNull(role) && role.equals("pending");
        String string = MyApplication.getInstance().getUserInfo();
        if (BaseMethod.notNull(string) && BaseUtils.isJSONValid(string)) {
            UserBean userBean = gson.fromJson(string, UserBean.class);
            boolean refereeRole = userBean.isReferee();
            if (refereeRole) {
                if (notJoin) {
                    mLlBtn.setVisibility(View.VISIBLE);
                    mTvApplayMainJudge.setVisibility(View.VISIBLE);
                    mTvApplayJudge.setVisibility(View.VISIBLE);
                    mTvApplayJudgeReviewing.setVisibility(View.GONE);
                    mTvApplayJudgeExit.setVisibility(View.GONE);
                } else if (pReferee || referee || customerReferee || pending) {
                    mLlBtn.setVisibility(View.VISIBLE);
                    if (statusId == 2) {
                        mTvApplayMainJudge.setVisibility(View.GONE);
                        mTvApplayJudge.setVisibility(View.GONE);
                        mTvApplayJudgeReviewing.setVisibility(View.VISIBLE);
                        mTvApplayJudgeExit.setVisibility(View.GONE);
                    } else if (statusId == 3) {
                        mTvApplayMainJudge.setVisibility(View.GONE);
                        mTvApplayJudge.setVisibility(View.GONE);
                        mTvApplayJudgeReviewing.setVisibility(View.GONE);
                        mTvApplayJudgeExit.setVisibility(View.VISIBLE);
                    }
                } else if (player || customer) {
                    mLlBtn.setVisibility(View.GONE);
                }
            } else {
                mLlBtn.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }
}
